const axios = require("axios");
const fs = require("fs");
const data = require("./process-data");

const baseUrl = "http://prts.wiki/w/";
const dataDir = "../data";

function fetchData(url, option = {}) {
  return axios.get(url, option);
}

function localizeData(data, fileName) {
  let savePath = dataDir + "/" + fileName;
  fs.writeFile(savePath, data, (err) => {
    if (err) {
      console.error(err);
    }
    console.log("保存" + fileName + "成功！");
  });
}

function fetchHeroList() {
  const url = encodeURI("干员一览");
  const fileName = "干员一览.html";
  fetchData(baseUrl + url)
    .then((response) => {
      if (response.status === 200) {
        localizeData(response.data, fileName);
      }
    })
    .catch((err) => {
      console.error(err);
    })
    .then(() => setTimeout(() => {}, 5000));
}

function fetchHeroDetail(hero, fileName) {
  return new Promise((resolve, reject) => {
    axios.get(hero).then((response) => {
      if (response.status === 200) {
        localizeData(response.data, fileName);
        resolve(response.data);
      } else {
        reject(response.status);
      }
    });
  });
}

function fetchAllHero(heros) {
  const req = heros.map((hero) =>
    fetchHeroDetail(baseUrl + encodeURI(hero), dataDir + "/" + hero + ".html")
  );
  Promise.all(req).then((values) => {
    console.log(values.length);
  });
}

function main() {
  // fetchHeroList();
  // data
  //   .heros()
  //   .then((data) => {
  //     fetchAllHero(data);
  //   })
  //   .catch((err) => {
  //     console.error(err);
  //   });
}

main();

exports.dataDir = dataDir;
